package com.lemon.lemonai.controller;

import com.lemon.lemonai.repository.impl.InMemoryChatHistoryRepository;
import com.lemon.lemonai.entity.vo.MessageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 查询历史会话记录
 * @Author: lemon
 * @CreateTime: 2025-03-22  21:42
 * @Version: 1.0
 */
@RestController
@RequestMapping("/ai/history")
@RequiredArgsConstructor
public class ChatHistoryController {

    private final InMemoryChatHistoryRepository chatHistoryRepository;

    private final ChatMemory chatMemory;

    /**
     * 查询历史会话列表（chatIds）
     * @param type
     * @return
     */
    @GetMapping("/{type}")
    public List<String> getChatIds(@PathVariable("type") String type){
        return chatHistoryRepository.getChatIds(type);
    }


    /**
     * 根据会话id查询历史会话
     * @param type
     * @param chatId
     * @return
     */
    @GetMapping("/{type}/{chatId}")
    public List<MessageVO> getChatHistory(@PathVariable("type") String type,
                                          @PathVariable("chatId") String chatId){
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if(messages.isEmpty()){
            return List.of();
        }
        return messages.stream().map(MessageVO::new).collect(Collectors.toList());
    }
}
